﻿
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using Yunchang;

namespace AutoChess
{
    class ShipRenderer : MonoBehaviour, IVisualRenderer<ShipUnit, ShipRenderer>
    {
        public ShipUnit shipUnit;
        private ShipModelKit shipModelKit;
        private ShipBehaviourCtr ctr;

        public GameObject fireBone, bulletBone, hitBone;

        private CommonEffect tiredEffect,damageEffect;

        public ShipModelKit ShipModelKit
        {
            get { return shipModelKit; }
        }

        private void Register()
        {
            EventManager.AddEventListener<bool>(CommonEvent.ON_SHIP_LEVEL_UPGRADES, PlayerShipUpEffect);
            EventManager.AddEventListener(CommonEvent.ON_SHIP_TIRED_EVENT, OnShipTiredEvent);
        }
        private void UnRegister()
        {
            EventManager.RemoveEventListener<bool>(CommonEvent.ON_SHIP_LEVEL_UPGRADES, PlayerShipUpEffect);
            EventManager.RemoveEventListener(CommonEvent.ON_SHIP_TIRED_EVENT, OnShipTiredEvent);
        }

        //回合疲劳
        private void OnShipTiredEvent()
        {
            if (AutoChessManager.Ins.cacheData.CurPlayerData.GUID != shipUnit.GetShipUnit().playerGuid)
                return;
            var round = AutoChessManager.Ins.cacheData.RoundNum;
            var table = Table.Blo.AutoChessBlo.GetTableAutoChessRound(round);
            if (table != null)
            {
                if (table.costHp > 0)
                {
                    tiredEffect = CommonEffectManager.Instance.PlayEffectImmediate(CommonEffectResId.AC_Thunder, transform);
                    SceneUIManager.Instance.OpenUI(transform, true, "AutoChessShipHitUI", table.costHp);
                }
            }
        }
        public void OnConnect(ShipUnit data)
        {
            if (shipModelKit == null)
            {
                shipModelKit = gameObject.AddMissingComponent<ShipModelKit>();
            }
            if (fireBone == null)
            {
                fireBone = new GameObject("FireBone");
                fireBone.transform.SetParent(transform);
                fireBone.transform.Normalize();
            }
            if (bulletBone == null)
            {
                bulletBone = new GameObject("BulletBone");
                bulletBone.transform.SetParent(transform);
                bulletBone.transform.Normalize();
            }
            if (hitBone == null)
            {
                hitBone = new GameObject("HitBone");
                hitBone.transform.SetParent(transform);
                hitBone.transform.Normalize();
            }
            this.shipUnit = data;
            if (shipUnit != null)
            {
                ctr = new ShipBehaviourCtr(this);
                transform.name = shipUnit.ToString();
                LoadShipModel();
                UpdatePosition();
                gameObject.SetActive(true);
                // 获取当前血量
                RefreshHpEffect();
                Register();
            }
        }

        

        private void LoadShipModel()
        {
            string modelRes = string.Empty;
            float modelScale = 1 * 0.3f;
            Vector3 offset = Vector3.zero;
            var dictShip = Table.Blo.TableShipBlo.GetTableShip(shipUnit.ShipId);
            if (dictShip != null)
            {
                var dictShipModel = Table.Blo.TableShipBlo.GetTableShipModel(dictShip.modelId);
                if (dictShipModel != null)
                {
                    var dictModel = Table.Blo.TableSailorModelBlo.GetTableSailorModel(dictShipModel.ModelId);
                    if (dictModel != null)
                    {
                        modelRes = dictModel.ModelRes;
                    }
                    else
                    {
                        Debug.LogError(string.Format("船只ModelId:{0} 模型资源不存在!", dictShipModel.ModelId));
                    }
                    offset = UtilityHelper.GetShipModelOffset(dictShip.modelId, shipUnit.IsLeft);
                    //var config = GameModeFieldRenderer.Ins.SceneConfig.GetShipConfig(dictShip.modelId);
                    modelScale = UtilityHelper.GetShipScale(dictShip.modelId);
                }
                else
                {
                    Debug.LogError(string.Format("船只ModelId:{0} 不存在--ShipId:{1}!", dictShipModel.ModelId, shipUnit.ShipId));
                }
            }
            else
            {
                Debug.LogError(string.Format("船只Id:{0} 不存在!",shipUnit.ShipId));
            }
            shipModelKit.SetModel(modelRes, transform);
            shipModelKit.SetModelAngle(new Vector3(0, 180, 0));
            shipModelKit.SetOffset(offset);
            shipModelKit.SetModelScale(modelScale);
            shipModelKit.afterLoad = () =>
            {
                shipModelKit.PlayAnimation("stand", false);
                shipModelKit.AddReflectionCompoment();
            };
        }

        public void OnDisconnect()
        {
            if (shipUnit != null)
            {
                transform.SetParent(AutoChessFieldViewCtr.Ins.ShipUnitRoot);
                transform.Normalize();
                UnRegister();
                if (tiredEffect != null)
                {
                    tiredEffect.Clear();
                    tiredEffect = null;
                }
                if (damageEffect != null)
                {
                    damageEffect.Clear();
                    damageEffect = null;
                }
            }
            shipUnit = null;
            transform.SetUnused(false, GameConst.AC_SHIP);
        }

        public void AutoPath(CommonAnimCurve cure, Action endCall)
        {
            var package = new MovePackage(cure, endCall);
            ctr.SwitchMoveState(package);
        }

        public void FireTarget(CommonAnimCurve cure, ShipUnit target)
        {
            var package = new ShipFirePackage(target, cure);
            ctr.SwitchFireState(package);
        }

        public void OnHit(HitData hitData)
        {
            hitBone.transform.position = hitData.hitPos;
            CommonEffectManager.Instance.PlayEffectImmediate(CommonEffectResId.AC_Ship_Be_Hit, hitBone.transform);

            SceneUIManager.Instance.OpenUI(transform, true, "AutoChessShipHitUI", AutoChessManager.Ins.cacheData.CurPlayerData.oneFightResult.costHp);

            // 获取当前血量
            var player = shipUnit.GetShipUnit();
            if (player != null)
            {
                ACPlayerData playerData;
                if (AutoChessManager.Ins.cacheData.playerMap.TryGetValue(player.playerGuid, out playerData))
                {
                    if (playerData.HP <= 80)
                    {
                        damageEffect= CommonEffectManager.Instance.PlayEffectImmediate(CommonEffectResId.AC_Ship_Damage_1, fireBone.transform);
                    }
                    if (playerData.HP <= 50)
                    {
                        damageEffect = CommonEffectManager.Instance.PlayEffectImmediate(CommonEffectResId.AC_Ship_Damage_2, fireBone.transform);
                    }
                    if (playerData.HP <= 20)
                    {
                        damageEffect = CommonEffectManager.Instance.PlayEffectImmediate(CommonEffectResId.AC_Ship_Damage_3, fireBone.transform);
                    }
                }
            }
        }
        private void RefreshHpEffect()
        {
            var player = shipUnit.GetShipUnit();
            if (player != null)
            {
                ACPlayerData playerData;
                if (AutoChessManager.Ins.cacheData.playerMap.TryGetValue(player.playerGuid, out playerData))
                {
                    bool isLeft = playerData.GUID == AutoChessManager.Ins.cacheData.CurPlayerData.GUID;

                    if (playerData.HP <= 80)
                    {
                        Vector3 offset = isLeft ? new Vector3(1.5f, 3, 0) : new Vector3(-1.5f, 3, 0);
                        damageEffect = CommonEffectManager.Instance.PlayEffectImmediate(CommonEffectResId.AC_Ship_Damage_1, fireBone.transform, (obj) => { obj.transform.localPosition = offset; });
                    }
                    if (playerData.HP <= 50)
                    {
                        Vector3 offset = isLeft ? new Vector3(1f, 4, 0) : new Vector3(-1f, 4, 0);
                        damageEffect = CommonEffectManager.Instance.PlayEffectImmediate(CommonEffectResId.AC_Ship_Damage_2, fireBone.transform, (obj) => { obj.transform.localPosition = offset; });
                    }
                    if (playerData.HP <= 20)
                    {
                        Vector3 offset = isLeft ? new Vector3(1.5f, 3, 0) : new Vector3(-1.5f, 3, 0);
                        damageEffect = CommonEffectManager.Instance.PlayEffectImmediate(CommonEffectResId.AC_Ship_Damage_3, fireBone.transform, (obj) => { obj.transform.localPosition = offset; });
                    }
                }
            }
        }
        private void Update()
        {
            if (ctr != null)
            {
                ctr.UpdateState();
            }
        }

        private void OnDestroy()
        {
            shipModelKit.ClearModel();
            shipModelKit = null;
        }

        public void RefreshRenderer()
        {
        }

        private void UpdatePosition()
        {
            if (shipUnit != null)
            {
                transform.position = shipUnit.Position;
            }
        }

        private void PlayerShipUpEffect(bool isUpgrade)
        {
            if (isUpgrade)
            {
                var player = shipUnit.GetShipUnit();
                if (player != null)
                {
                    bool isLeft = player.playerGuid == AutoChessManager.Ins.cacheData.CurPlayerData.GUID;
                    if (isLeft)
                    {
                        CommonEffectManager.Instance.PlayEffectImmediate(CommonEffectResId.AC_Ship_Upgrade, fireBone.transform);
                    }
                }
            }
        }
    }
}
